package webmarket.controller;

import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import webmarket.common.JSONMapper;
import webmarket.common.MarkerController;
import webmarket.common.MarkerController.MarkerTypes;
import webmarket.common.UserInfoMessages;
import webmarket.common.ValidationObject;
import webmarket.common.exception.NonexistentEntityException;
import webmarket.jpacontrollers.UserJpaController;
import webmarket.model.User;

/**
 * 
 * Controller of the 'login/*' and 'logout' view
 *
 */
@Controller
public class LoginController extends ControllerBase {
	@RequestMapping(method=RequestMethod.GET, value="/")
	public String _default(){
		return "redirect:login";
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/login")
	public ModelAndView login(ModelMap model){
		return new ModelAndView("login",model);
	}

	@RequestMapping(method = RequestMethod.GET, value = "/login/denied")
	public ModelAndView accessdenied(ModelMap model) {
		JSONMapper mapper = new JSONMapper();
		String msg = UserInfoMessages.LOGIN_DENIED;
		mapper.put("userinfo", ValidationObject.error("userinfo", msg));
		model.put("json", mapper.WriteJSON());
		logger.warn(MarkerController.getMarker(MarkerTypes.LOGIN_INVALID),
				"Sikertelen bejelentkezés");
		return new ModelAndView("login",model);
	}

	@RequestMapping(method = RequestMethod.GET, value = "/login/success")
	public ModelAndView success(ModelMap model, HttpServletRequest request) throws NonexistentEntityException {
		UserJpaController userJpaController = new UserJpaController();
		User user = userJpaController.getCurrent();
		user.setLastlogin(new Timestamp(new Date().getTime()));
		userJpaController.edit(user);
		JSONMapper mapper = new JSONMapper();
		mapper.put("userinfo", ValidationObject.success("userinfo", UserInfoMessages.LOGIN_SUCCESS));
		model.put("json", mapper.WriteJSON());
		logger.info(MarkerController.getMarker(MarkerTypes.LOGIN),
				"Sikeres bejelentkezés");
		return new ShopController().shop_main(model);
	}

	@RequestMapping(method = RequestMethod.GET, value = "/logout")
	public ModelAndView logout(ModelMap model, HttpServletRequest request) {
		JSONMapper mapper = new JSONMapper();
		mapper.put("userinfo", ValidationObject.success("userinfo", UserInfoMessages.LOGOUT_SUCCESS));
		model.put("json", mapper.WriteJSON());
		logger.info(MarkerController.getMarker(MarkerTypes.LOGOUT),
				"Felhasználó kijelentkezett");
		return new ModelAndView("login",model);
	}
}
